package com.example.Repository.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Repository.UserRepository;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.pojo.dto.LoginDto;
import com.example.pojo.dto.RegisterDto;
import com.example.pojo.vo.LoginUser;
import com.example.pojo.vo.UserVo;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author crt
 */
@Service
public class UserRepositoryImpl implements UserRepository {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result register(RegisterDto registerDto) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",registerDto.getUsername());
        User u = userService.getOne(wrapper);
        if(u == null ){
            String encode = passwordEncoder.encode(registerDto.getPassword());
            //String md6String = Md5Util.getMD5String(password);
            User user = new User();
            user.setUsername(registerDto.getUsername());
            user.setPassword(encode);
            userService.save(user);
            return Result.success();
        }else {
            return Result.error("用户名已被占用");
        }
    }

    @Override
    public Result<String> login(LoginDto loginDto) throws Exception {
        User user = new User();
        user.setUsername(loginDto.getUsername());
        user.setPassword(loginDto.getPassword());

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if(Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String loginUserString = JSON.toJSONString(loginUser);
        String jwt = JwtUtil.createJWT(loginUserString, null);

        //token 存储进Redis
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(jwt,jwt,1, TimeUnit.HOURS);

//        String jwt = userService.login(user);
        if(StringUtils.hasText(jwt)){
            return Result.success(jwt);
        }
        return Result.error("登录失败");
    }

    @Override
    public Result<UserVo> getUserInfo(String username) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username",username));
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return Result.success(userVo);
    }
}
